<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class IntermediaryModel extends Model
{
    use HasFactory;
    protected $table = 'intermediary_user';
    protected $guarded=[];
    public static function getAllbrokerData($id = null)
    {
        $brokerData = self::with(['company','house'])
            ->where('status', 1) //经纪人状态
            ->when($id,function ($query)use($id){//查询具体某个经纪人
                $query->where('id',$id);
            })
            ->get()->toArray();

        if ($id == null) return $brokerData;
        //当前时间戳
        $time = time();
        //获取非顶级的房源属性
        $houseattrData = Houseattr::where('pid', '>', 0)->get()->pluck('name', 'id');
        //循环房源数据
        foreach ($brokerData[0]['house'] as $k => &$v) {
            //匹配房源属性
            foreach ($houseattrData as $kk => $vv) {
                if ($v['house_room'] == $kk) $v['house_room'] = $vv;
                if ($v['house_direction'] == $kk) $v['house_direction'] = $vv;
                if ($v['house_floor'] == $kk) $v['house_floor'] = $vv;
            }
            //获取发布的时间戳
            $addTime = strtotime($v['created_at']);
            //获取发布时间到现在时间的时间戳
            $diffTime = $time - $addTime;
            //判断发布时间
            switch ($diffTime) {
                case $diffTime >= 0 && $diffTime < 60 :
                    $v['time'] = '刚刚';
                    break;
                case $diffTime >= 60 && $diffTime < 60 * 60 * 2:
                    $v['time'] = '2小时前';
                    break;
                case $diffTime >= 60 * 60 * 2 && $diffTime < 3600 * 24 * 2:
                    $v['time'] = '2天前';
                    break;
                case $diffTime >= 3600 * 24 * 2 && $diffTime < 3600 * 24 * 7:
                    $v['time'] = '1周前';
                    break;
                default:
                    $v['time'] = date('Y-m-d H:i:s', $addTime);
                    break;
            }
        }

        return $brokerData;
    }

    /**
     * 一个经纪人属于一家公司
     */
    public function company()
    {
        return $this->belongsTo(Company::class, 'company', 'id');
    }

    /**
     * 一个经纪人可以对应多个房源
     */
    public function house()
    {
        return $this->hasMany(House::class,'intermediary_id','id');
    }


}
